package com.jianganming.netty.chat;

import com.alibaba.fastjson.JSONObject;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class ChatClient {
    public static void main(String[] args) {
        EventLoopGroup group = new NioEventLoopGroup();

        try {

            Bootstrap bootstrap = new Bootstrap();
            ChannelFuture future = bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast("decoder",new StringDecoder());
                            pipeline.addLast("encoder",new StringEncoder());
                            pipeline.addLast(new MyClientHandler());
                        }
                    }).connect("127.0.0.1", 8887)
                    .sync();
            Channel channel = future.channel();
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name","王丰山");
                jsonObject.put("msg",scanner.next());
                channel.writeAndFlush(jsonObject.toJSONString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }
}

class MyClientHandler extends SimpleChannelInboundHandler<String>{

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(s);
        System.out.println(jsonObject.getString("name")+"  说：");
        System.out.println(jsonObject.getString("msg"));
    }
}
